public class Solution59 {
    public int[][] generateMatrix(int n) {
        int up = 0, down = n - 1, left = 0, right = n - 1;
        int[][] res = new int[n][n];
        for (int k = 1; k <= n * n; ) {
            for (int i = left; i <= right; i++) {
                res[up][i] = k;
                k++;
            }
            up++;

            for (int i = up; i <= down; i++) {
                res[i][right] = k;
                k++;
            }
            right--;

            for (int i = right; i >= left; i--) {
                res[down][i] = k;
                k++;
            }
            down--;

            for (int i = down; i >= up; i--) {
                res[i][left] = k;
                k++;
            }
            left++;
        }
        return res;
    }
}
